package cn.rainbow.modules.sys.service.impl;

import cn.rainbow.common.utils.Constant;
import cn.rainbow.common.utils.PageUtils;
import cn.rainbow.common.utils.Query;
import cn.rainbow.modules.sys.dao.SysAddrDao;
import cn.rainbow.modules.sys.entity.SysAddrEntity;
import cn.rainbow.modules.sys.service.SysAddrService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;


/**
 * 系统用户
 * 
 * @author   7sh
 * @email   dev@7sh.cn
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysAddrService")
public class SysAddrServiceImpl extends ServiceImpl<SysAddrDao, SysAddrEntity> implements SysAddrService {


	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String keywords = (String)params.get("keywords");

		Page<SysAddrEntity> page = this.selectPage(
			new Query<SysAddrEntity>(params).getPage(),
			new EntityWrapper<SysAddrEntity>()
				.andNew()
					.like(StringUtils.isNotBlank(keywords),"recipients", keywords).or()
					.like(StringUtils.isNotBlank(keywords),"mobile", keywords)
		);

		return new PageUtils(page);
	}

	@Override
	public void save(SysAddrEntity addr) {

		addr.setIsDeleted(Constant.IsDeleted.NO.getValue());
		addr.setCreateDate(new Date());

		if(null != addr.getFlagList() && addr.getFlagList().size() > 0) {
			String flag = "";
			flag = StringUtils.join(addr.getFlagList().toArray(),",");
			addr.setFlag(flag);
		}

		this.insert(addr);
	}

	@Override
	public void update(SysAddrEntity addr) {
		addr.setUpdateDate(new Date());

		if(null != addr.getFlagList() && addr.getFlagList().size() > 0) {
			String flag = "";
			flag = StringUtils.join(addr.getFlagList().toArray(),",");
			addr.setFlag(flag);
		}else {
			addr.setFlag("");

		}

		this.updateById(addr);

	}

	@Override
	public void deleteBatch(Long[] ids) {

		this.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public SysAddrEntity selectById(Serializable id) {

		SysAddrEntity sysAddrEntity = super.selectById(id);

		if(StringUtils.isNotBlank(sysAddrEntity.getFlag())) {
			String [] flags = sysAddrEntity.getFlag().split(",");
			List<String> list = new ArrayList<>();
			Collections.addAll(list, flags);
			sysAddrEntity.setFlagList(list);
		}

		return sysAddrEntity;
	}
}
